const params = new URLSearchParams(location.search);
const user_id = params.get('user_id'),
    type = params.get('type');
const onSiteColor = '#00C972',
    businessTripColor = '#3EA0FE',
    routationLeaveColor = '#ffa915',
    backgroundBlueColor = '#447FFF',
    splitColor = 'rgba(0, 0, 0, 0.3)';
let app = new Vue({
    el: '#app',
    components: {
        iInput: iview.Input,
        iPage: iview.Page,
        iSpin: iview.Spin,
        iIcon: iview.Icon,
    },
    mounted() {
        this.table_columns[0].text = this.getDateFormat(new Date());
        this.short_table_columns = JSON.parse(JSON.stringify(this.table_columns));
        this.short_table_columns.shift();
        if (user_id) {
            this.user_id = user_id;
            this.table_columns.shift();
            this.is_person_data = true;
            this.clickPerson({userId: user_id});
            $('.logo').hide();
        } else {
            this.getNavList(this.getGroupData);
        }
    },
    data: {
        current_nav: { key: type || 'on_site' },
        nav_list: [
            { key: 'on_site', text: 'On Site', num: 0, color: onSiteColor },
            { key: 'business_trip', text: 'Business Trip', num: 0, color: businessTripColor },
            { key: 'routation_leave', text: 'Routation Leave', num: 0, color: routationLeaveColor },
            {
                key: 'all_staff',
                text: 'All Staff',
                on_site: 0,
                business_trip: 0,
                routation_leave: 0,
                children: []
            },
        ],
        user_id: '',
        table_columns: [
            { text: '' },
            { text: 'Jan', can_sort: true },
            { text: 'Feb', can_sort: true },
            { text: 'Mar', can_sort: true },
            { text: 'Apr', can_sort: true },
            { text: 'May', can_sort: true },
            { text: 'Jun', can_sort: true },
            { text: 'Jul', can_sort: true },
            { text: 'Aug', can_sort: true },
            { text: 'Sep', can_sort: true },
            { text: 'Oct', can_sort: true },
            { text: 'Nov', can_sort: true },
            { text: 'Dec', can_sort: true },
            { text: 'Total', can_sort: true },
        ],
        short_table_columns: [],
        table_datas: [],
        search_name: '',
        page_data: {
            page: 1,
            total: 0,
            limit: 13
        },
        params: {},
        weekstart: 1,   // 第一列星期几
        type: 'status', // status/group/person
        year: new Date().getFullYear(),
        current_year: new Date().getFullYear(),
        current_person_data: {},
        week_datas: ['Mon', 'Tues', 'Wed', 'Thur', 'Fri', 'Sat', 'Sun'],
        month_datas: {
            list: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
            datas: []
        },
        is_person_data: false,
        getting_group_data: false,
        getting_person_data: false,
    },
    computed: {
        // 顶部星期栏目
        weekDay() {
            return this.week_datas.slice(this.weekstart - 1).concat(this.week_datas.slice(0, this.weekstart - 1));
        },
        pages() {
            const totalPages = Math.ceil(this.page_data.total / this.page_data.limit);
            return Array.from({ length: totalPages }, (_, i) => i + 1);
        },
    },
    methods: {
        getNavList: function (cb) {
            let vm = this;
            vm.nav_list[3].children = [];
            // 发送请求获取左边nav数据
            $.get('/seeyon/ebsRc.do?method=leadershipAgendaDepartment', {
                userId: window._currentUser.id,
                year: vm.year,
            })
            .done(function(res) {
                vm.nav_list[0].num = res.onSite;
                vm.nav_list[1].num = res.bt;
                vm.nav_list[2].num = res.rl;
                vm.nav_list[3].on_site = res.onSite;
                vm.nav_list[3].business_trip = res.bt;
                vm.nav_list[3].routation_leave = res.rl;
                res.allStaff.forEach(item => {
                    vm.nav_list[3].children.push({
                        key: item.deptId,
                        text: item.deptName,
                        on_site: item.onSite,
                        business_trip: item.bt,
                        routation_leave: item.rl
                    });
                });
                cb();
            })
        },
        clickNav: function (nav, type) {
            if (this.getting_group_data) return;
            this.current_nav = nav;
            this.type = type;
            this.current_person_data = {};
            this.getGroupData(false);
        },
        clickPerson: function (item) {
            if ((!item || !item.user_id) && !user_id) return;
            let vm = this;
            if (vm.user_id) {
                vm.type = 'person';
                vm.year = new Date().getFullYear();
                vm.current_person_data.user_id = vm.user_id;
                vm.getPersonData(vm.user_id);
                vm.scrollToElement('target');
            } else if (item.user_id == vm.current_person_data.user_id) {
                vm.type = 'group';
                vm.current_person_data = {};
                vm.getGroupData(false, vm.page_data.page);
            } else {
                vm.type = 'person';
                vm.current_person_data = item;
                vm.getPersonData();
                vm.scrollToElement('target');
            }
        },
        scrollToElement: function (id) {
            const element = document.getElementById(id);
            if (element) {
                element.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });
            }
        },
        changeYear: function (num) {
            let vm = this;
            if (vm.year == 2024 && num == -1) return;
            // 显示单人数据的时候不清除列表
            if (!vm.current_person_data.user_id) {
                vm.table_datas = [];
            }
            vm.month_datas.datas = [];
            vm.year = vm.year + num;
            if (vm.current_person_data.user_id) {
                vm.getPersonData();
            } else {
                vm.getGroupData(false);
            }
        },
        changePage: function (page) {
            this.getGroupData(false, page, this.params);
        },
        getGroupData: function (flag, page, params) {
            let vm = this;
            if (vm.getting_group_data) return;
            if (!params) {
                params = {};
                // 所有列的sort恢复未选择的状态
                for (let i = 0; i < this.table_columns.length; i++) {
                    if (this.table_columns[i].can_sort) {
                        this.table_columns[i].sort = '';
                    }
                }
            }
            vm.table_datas = [];
            vm.page_data.page = page || 1;
            let state = '', deptId = '';
            // 根据当前选择的nav来获取state和deptId的具体值，因为部门是在所有状态中查找，所以这两个参数不会同时存在值
            if (vm.type === 'status') {
                // 设置state值
                switch (vm.current_nav.key) {
                    case 'business_trip':
                        state = 1;
                        break;
                    case 'on_site':
                        state = 2;
                        break;
                    case 'routation_leave':
                        state = 3;
                        break;
                    default:
                }
            } else if (!flag && vm.type === 'group') {
                // 设置deptId值
                deptId = vm.current_nav.key;
            } else if (flag) {
                if (['on_site', 'business_trip', 'routation_leave'].indexOf(vm.current_nav.key) != -1) {
                    vm.type = 'status';
                } else {
                    vm.type = 'group';
                }
                if (['on_site', 'business_trip', 'routation_leave', 'all_staff'].indexOf(deptId) == -1) deptId = vm.current_nav.key;
            }
            if (['on_site', 'business_trip', 'routation_leave', 'all_staff'].indexOf(deptId) != -1) deptId = '';
            // 发送请求，获取列表数据table_datas
            vm.getting_group_data = true;
            $.get('/seeyon/rcyh.do?method=leadershipAgendaPerson', {
            // $.get('/seeyon/ebsRc.do?method=leadershipAgendaPerson', {
                userId: window._currentUser.id,
                year: vm.year,
                state, // 1-出差  2-在岗  3-请假
                page: vm.page_data.page,
                limit: vm.page_data.limit,
                deptId, // 部门id    
                name: vm.search_name, // 模糊查询名字
                ...params, // 排序参数
            })
            .done(function(res) {
                vm.page_data.total = res.countNum;
                res.userInfo.forEach(info => {
                    let status ='', month_datas = [];
                    switch (info.state) {
                        case 1:
                            status = 'trip';
                            break;
                        case 2:
                            status = 'on-site';
                            break;
                        case 3:
                            status = 'leave';
                            break;
                        case 4:
                            status = 'trip';
                            break;
                        default:
                            // status = 'default';
                            status = 'on-site';
                    }
                    vm.short_table_columns.forEach(month => {
                        let item = info.monthInfo[month.text];
                        month_datas.push({
                            on_site: item && item.onSite || 0,
                            business_trip: item && item.bt || 0,
                            routation_leave: item && item.rl || 0,
                        });
                    });
                    vm.table_datas.push({
                        user_id: info.userId,
                        name: info.userName,
                        status,
                        month_datas
                    });
                });
                let length = vm.table_datas.length;
                if (length < vm.page_data.limit) {
                    for (let k = 0; k < vm.page_data.limit - length; k++) {
                        vm.table_datas.push({});
                    }
                }
                vm.getting_group_data = false;
            })
        },
        getPersonData: function (user_id) {
            let vm = this;
            if (vm.getting_person_data) return;
            vm.month_datas.datas = {};
            vm.getting_person_data = true;
            $.get('/seeyon/rcyh.do?method=personalSchedule', {
                userId: vm.current_person_data.user_id,
                year: vm.year
            })
            .done(function(res) {
                // 赋值datas和table_datas
                vm.getting_person_data = false;
                res = JSON.parse(res);
                let month_detail = res.month_detail;
                vm.month_datas.list.forEach((month, index) => {
                    if (!vm.month_datas.datas[month]) {
                        vm.month_datas.datas[month] = month_detail[month] || {
                            all_data: [],
                            on_site_data: [],
                            homeTrip_data: [],
                            trip_data: [],
                            leave_data: []
                        }
                    }
                    if (!vm.month_datas.datas[month]['all_data'] || !vm.month_datas.datas[month]['all_data'].length) {
                        vm.month_datas.datas[month]['all_data'] = vm.getAllDatesInMonth(vm.year, index);
                    }
                });
                let month_datas = [];
                vm.short_table_columns.forEach((month, index) => {
                    let month_data = res.month_datas[month.text];
                    month_datas.push({
                        on_site: month_data && month_data.onSite || 0,
                        business_trip: month_data && month_data.bt || 0,
                        routation_leave: month_data && month_data.rl || 0,
                        is_total: month.text == 'Total'
                    });
                });
                vm.current_person_data = {
                    user_id: res.userId,
                    name: res.userName,
                    status: res.dayState,// 0-无状态 1-出差 2-在岗 3-休假
                    month_datas: month_datas
                };
                if (vm.is_person_data) {
                    vm.table_datas = month_datas;
                }
            })
        },
        setSort: function (index, type) {
            let item = JSON.parse(JSON.stringify(this.table_columns[index]));
            if (item.sort == type) {
                this.table_columns[index].sort = '';
                this.getGroupData(false, 1)
            } else {
                let params = {
                    sortMonth: item.text,
                    sortType: type,     //排序类型  1-降序 2-升序
                };
                for (let i = 0; i < this.table_columns.length; i++) {
                    if (this.table_columns[i].can_sort) {
                        if (i == index) {
                            this.table_columns[i].sort = type;
                        } else if (this.table_columns[i].sort) {
                            this.table_columns[i].sort = '';
                        }
                    }
                }
                this.params = params;
                this.getGroupData(false, 1, params);
            }
        },
        getDateFormat: function (date) {
            let newDate = new Date(date);
            let year = newDate.getFullYear();
            let month = newDate.getMonth() + 1;
            let day = newDate.getDate();
            month = month >= 10 ? month : '0' + month;
            day = day >= 10 ? day : '0' + day;
            return year + '-' + month + '-' + day;
        },
        getAllDatesInMonth: function (y, m) {
            let vm = this;
            let firstDayOfMonth = new Date(y, m, 1).getDay() // 当月第一天星期几
            let lastDateOfMonth = new Date(y, m + 1, 0).getDate() // 当月最后一天
            let lastDayOfLastMonth = new Date(y, m, 0).getDate() // 上一月的最后一天
            let dates = [] // 所有渲染日历
            let weekstart = this.weekstart == 7 ? 0 : this.weekstart; // 方便进行日期计算，默认星期从0开始
            let startDay = (() => {
                // 周初有几天是上个月的
                if (firstDayOfMonth == weekstart) {
                    return 0
                } else if (firstDayOfMonth > weekstart) {
                    return firstDayOfMonth - weekstart
                } else {
                    return 7 - weekstart + firstDayOfMonth
                }
            })()
            let endDay = 7 - ((startDay + lastDateOfMonth) % 7) // 结束还有几天是下个月的
            for (let i = 1; i <= startDay; i++) {
                dates.push({
                    date: lastDayOfLastMonth - startDay + i,
                    day: weekstart + i - 1 || 7,
                    month: m - 1 >= 0 ? m - 1 : 12,
                    year: m - 1 >= 0 ? y : y - 1
                })
            }
            for (let j = 1; j <= lastDateOfMonth; j++) {
                dates.push({
                    date: j,
                    day: (j % 7) + firstDayOfMonth - 1 || 7,
                    month: m,
                    year: y,
                })
            }
            endDay = endDay == 7 ? 0 : endDay;
            for (let k = 1; k <= endDay; k++) {
                dates.push({
                    date: k,
                    day: (lastDateOfMonth + startDay + weekstart + k - 1) % 7 || 7,
                    month: m + 1 <= 11 ? m + 1 : 0,
                    year: m + 1 <= 11 ? y : y + 1
                })
            }
            return dates
        },
        isThisMonth(date_item, index) {
            let date = new Date(this.year, index);
            return date_item.year == date.getFullYear() && date_item.month == date.getMonth();
        },
        getStyle(date_item, month_data, index) {
            let vm = this;
            let data = vm.month_datas.datas[month_data];
            let color = '', background = '', display = 'block', border = '';
            let d1 = new Date(date_item.year, date_item.month, date_item.date);
            function isSameDay(d1, date) {
                return d1.getFullYear() == date.getFullYear() && d1.getMonth() == date.getMonth() && d1.getDate() == date.getDate();
            }
            data.on_site_data.forEach(item => {
                let date = new Date(item);
                if (isSameDay(d1, date)) {
                    background = onSiteColor;
                }
            });
            data.leave_data.forEach(item => {
                let date = new Date(item);
                if (isSameDay(d1, date)) {
                    background = routationLeaveColor;
                }
            });
            data.homeTrip_data.forEach(item => {
                let date = new Date(item);
                if (isSameDay(d1, date)) {
                    background = businessTripColor;
                    border = '1px solid rgba(2, 29, 178, 1)';
                }
            });
            data.trip_data.forEach(item => {
                let date = new Date(item);
                if (isSameDay(d1, date)) {
                    background = businessTripColor;
                    border = '1px solid ' + businessTripColor;
                }
            });
            if (background) {
                color = '#fff';
            }
            if (!vm.isThisMonth(date_item, index)) {
                color = 'rgba(0, 0, 0, 0.3)';
                background = '#fff';
                display = 'none';
            }
            return { 'color': color, 'background': background, 'border': border, 'display': display }
        },
        getHtml(date_item, month_data, index) {
            let vm = this;
            let data = vm.month_datas.datas[month_data];
            let style = {color: '', background: '', display: 'flex', border: ''};
            let d1 = new Date(date_item.year, date_item.month, date_item.date);
            function isSameDay(d1, date) {
                return d1.getFullYear() == date.getFullYear() && d1.getMonth() == date.getMonth() && d1.getDate() == date.getDate();
            }
            let html = '';
            let height = 16;
            let commonTripStyle = `width:${height}px;height:${height}px;border:1px solid #fff;border-radius: ${height}px;line-height:14px;display: flex;justify-content: center;align-items: center;`;
            data.on_site_data.forEach(item => {
                let date = new Date(item);
                if (isSameDay(d1, date)) {
                    style.background = onSiteColor;
                    html += date_item.date;
                }
            });
            data.leave_data.forEach(item => {
                let date = new Date(item);
                if (isSameDay(d1, date)) {
                    style.background = routationLeaveColor;
                    html += date_item.date;
                }
            });
            data.homeTrip_data.forEach(item => {
                let date = new Date(item);
                if (isSameDay(d1, date)) {
                    style.background = businessTripColor;
                    style.border = '2px solid #5579FF';
                    html += `<p style="${commonTripStyle}background:${businessTripColor}">${date_item.date}</p>`;
                    height = 20;
                }
            });
            data.trip_data.forEach(item => {
                let date = new Date(item);
                if (isSameDay(d1, date)) {
                    style.background = businessTripColor;
                    style.border = '2px solid #7BBEFF';
                    html += `<p style="${commonTripStyle}background:${businessTripColor}">${date_item.date}</p>`;
                    height = 20;
                }
            });
            if (style.background) {
                style.color = '#fff';
            }
            if (!vm.isThisMonth(date_item, index)) {
                style.color = 'rgba(0, 0, 0, 0.3)';
                style.background = '#fff';
                style.display = 'none';
            }
            html = html || date_item.date;
            return `<div style="display: flex;justify-content: center;align-items: center;width: ${height}px; height: ${height}px;border-radius: 100%; color:${style.color}; background: ${style.background}; display: ${style.display}; border: ${style.border}">${html}</div>`;
        },
    }
})